<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户类  
 */
class User extends CI_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->library('request');  //自定义
        $this->load->library('response'); //自定义
        $this->load->library('session'); //公共
        $this->load->library('weixin'); //微信 
    }   

     /**
     * 用户首次进入小程序、或者再次进入小程序
     * [通过code，appid，appsecret获取登录信息：openid，sesssionkey]
     * 登陆后，session中存放：sf_session_key:userid,openid等唯一信息存在数据库中
     * 如果携带了sf_session_key，则说明是再次登录，去session中查openid等
     * 请求路径：jizhang/login/wxLogin
     * 类型：post
     * 入参：
     *     code：微信小程序通过API（wx.login），获取的code
     *     sf_session_key：第一次传空，接口登录成功，会在出参返回：必传
     *     nick：昵称
     *     head：头像 
     * 出参：
     * {
            "status": 0,
            "desc": "成功",
            "out_data": {
                "sf_session_key": "SE1325969963"   唯一标识，再次登录的时候，传入
            }
        }
     * @return [type] [description]
     */
    public function wxLogin(){
        $reqData = $this->request->getPostRawData();
        if(!isset($reqData['code']) || !isset($reqData['sf_session_key'])){
            $this->response->sendData(1000);return;
        }
        //参数没问题 
        $this->load->model("userModel");
        log_message('info', 'user/wxLogin,data:'.json_encode($reqData));    
        
        //检查登陆状态
        $retStatus =  $this->userModel->loginStatus($reqData);
        $status = $retStatus['status'];
        //要么是第一次login，要么是登录失效，重新登录，需要code值
        if($status!=0){
            //传输了code，可以去微信登录了 
            $ret = $this->loginWX($reqData['code']);
            // var_dump($ret);exit;
            log_message('info', 'wxLogin,login,ret:'.json_encode($ret));    
            
               // 。。。。  测试  。。。。//
               // $ret['status'] = 0;
               // $ret['out_data']['openid'] = 'oLQAn0XYLvNSs_aThEYnkfbk3p3k';
               // $ret['out_data']['session_key'] = 'tiSXXyKrZpT9hqLATCDSKw==';
            
            if($ret['status']){            
                $status = $ret['status'];
                $this->response->sendData($status);return;
            }
            else{
                //登录成功
                $adduserret = $this->userModel->addUser($ret['out_data']['openid'],$ret['out_data']['session_key'],$reqData['head'],$reqData['nick']);  
                $status = $adduserret['status'];
            }
            $retData['sf_session_key'] = $adduserret['out_data']['sf_session_key'];
            $this->response->sendData($status,"",$retData);

        }
        else{
            $retData['sf_session_key'] = $reqData['sf_session_key'];
            $this->response->sendData($status,"",$retData);
        }
        
        
    }

     /**
     * 微信登录
     * 使用code，登录，也可能是超时重新登录
     */
    private function loginWX($code){
        // echo $code;exit;
        $url = $this->weixin->wxSmallLogin($code);
        $request = $this->request->http_get($url);
        $bodyArr = json_decode($request,true);
        // var_dump($bodyarr);exit;
        if(isset($bodyArr['errcode'])&&$bodyArr['errcode']&&$bodyArr['errmsg']){
            //有错误，
            $ret['status'] = 2007;
        }
        else{
            $ret['status'] = 0;
            $openid = isset($bodyArr['openid'])?$bodyArr['openid']:'';
            $session_key = isset($bodyArr['session_key'])?$bodyArr['session_key']:'';
            if($openid && $session_key){
                $ret['status'] = 0;
            }
            else{
                $ret['status'] = 2007;
            }
        }
        $ret['out_data'] = $bodyArr;
        return $ret;
    }

    // public function test(){
    //     if($this->input->method()=="post"){                
    //         if(1==1){
    //             $this->response->sendData(1000);    return;
    //         }
    //         $this->load->database();
    //         $ret = $this->input->post(array('id'), TRUE);
    //         // var_dump($ret);exit;
    //         $id = $ret['id'];
    //         $query = $this->db->get_where('user_base', array('id' => $id));
    //         var_dump($query->result());exit;

    //         $data = $this->request->getPostRawData();
    //         log_message('info', 'user/login,data:'.json_encode($data));     
    //         $id = $data['id'];
    //         $query = "SELECT id ,account,open_id,password,status FROM user_base where id = $id";
    //         // echo $query;exit;
    //         $info = $this->db->query($query);
    //         var_dump($info->result());exit;
    //     }
    //     else{
    //         $status = 1001;
    //     }
    //     $this->response->sendData($status);       
    // }
    // 
    // 
    
    /**
     * [commitStudent description]
     * @return [type] [description]
    */
    public function commitStudent(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/commitStudent,data:'.json_encode($reqData)); 
            if(!$reqData['schoolName'] || !$reqData['studentNo']){
                $this->response->sendData(1000);return;
            }
            //1验证登录状态
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;

            }
            // var_dump($retStatus);exit;
            $userId = $retStatus['userId'];
            
            //1是否已经认证过（待审核、审核成功）
            $extra = $this->userModel->extraInfo($userId);
            if(!isset($extra->id) || $extra->school_status==0 || $extra->school_status==1){
                $this->response->sendData(2015);return;
            }
            
            //2更新到user_extra中
            $extra = $this->userModel->updateSchool($userId,$reqData['schoolName'],$reqData['studentNo']);
            $status = 0;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }

     /**
     * [commitStudent description]
     * @return [type] [description]
    */
    public function commitIdentity(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/commitIdentity,data:'.json_encode($reqData)); 
            if(!$reqData['idNo'] || !$reqData['idName']){
                $this->response->sendData(1000);return;
            }
            //1验证登录状态
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;

            }
            $userId = $retStatus['userId'];
            
            //1是否已经认证过（待审核、审核成功）
            $extra = $this->userModel->extraInfo($userId);
            if(!isset($extra->id) || $extra->id_status==0 || $extra->id_status==1){
                $this->response->sendData(2016);return;
            }

            // $string = 'HTTP/1.1 200 OK
            //     Server: nginx/1.12.1
            //     Date: Wed, 07 Nov 2018 02:46:27 GMT
            //     Content-Type: application/json
            //     Content-Length: 133
            //     Connection: keep-alive
            //     Vary: Accept-Encoding

            //     {
            //       "data": {
            //         "check_code": "1", 
            //         "idcard": "372301198601053410", 
            //         "name": "\u674e\u6653\u680b"
            //       }, 
            //       "status": true
            //     }';
            // $pp =  explode("\r\n\r\n", $string, 2);
            // $qq = json_decode($pp[1],true);
            // var_dump($qq);exit;
            //2调用接口，去验证有效性
            $bodyArr['status'] = 0;
            $identityCheck = $this->config->item('identityCheck');
            // var_dump($identityCheck);exit;
            $url = $identityCheck['url'];
            $checkData = array(
                "name"=> $reqData['idName'],
                "idcard"=>$reqData['idNo'],
                "channel"=>$identityCheck['channel']  //公司信息
            );
            $checkDataJson = json_encode($checkData);
            // echo ($checkDataJson);exit;
            $checkRet = $this->request->http_post($url,$checkDataJson);
            // var_dump($checkRet);exit;
            log_message('info', 'user/commitIdentity,checkRet:'.$checkRet);
            if(!$checkRet){ 
                $this->response->sendData(2022);return;                
            }
            //发送成功，进行解析
            $retBody =  explode("\r\n\r\n", $checkRet, 2);
            log_message('info', 'user/commitIdentity,retBody:'.json_encode($retBody));
            if(count($retBody)!=2){
                $this->response->sendData(2022);return;   
            }
            //解析
            $retBodyData = json_decode($retBody[1],true);
            if($retBodyData['status'] && $retBodyData['data']['check_code']==="1"){
                //3true 代表认证通过，更新到user_extra中
                $extra = $this->userModel->updateIdentity($userId,$reqData['idNo'],$reqData['idName'],1);
                $status = 0;   
            }
            else{
                $this->response->sendData(2019);return;
            }
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }


   /**
     * [commitStudent description]
     * @return [type] [description]
    */
    public function userInfo(){
        if($this->input->method()=="get"){       
            $reqData = $this->request->getGetData();
            log_message('info', 'user/userInfo,data:'.json_encode($reqData)); 

            //1验证登录状态 
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;

            }
            $userId = $retStatus['userId'];
              
            $base = $this->userModel->baseInfo($userId);
            $extra = $this->userModel->extraInfo($userId);
            if(isset($extra->id) && isset($base->id)){
                $out_data['account'] = $base->account;
                $out_data['nick'] = $extra->nickname;
                $out_data['head'] = $extra->avatar;
                $out_data['email'] = $extra->email;
                $out_data['inviteCode'] = $extra->invite_code;
                $out_data['idNo'] = $extra->id_no;
                $out_data['idStatus'] = $extra->id_status;
                $out_data['idName'] = $extra->id_name;
                $out_data['schoolName'] = $extra->school_name;
                $out_data['schoolNo'] = $extra->school_no;
                $out_data['schoolStatus'] = $extra->school_status;
                $this->response->sendData(0,'',$out_data);return;
            }
            else{
                $status = 2000;
            }
          
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }





    // /**
    //  * [login description
    //  * 手机号，密码登陆,暂时不存在
    //  * 没有此种登陆方式]
    //  * @return [type] [description]
    //  */
    // public function login(){
    //     // if($this->input->method()=="post"){       
    //     //     $data = $this->request->getPostRawData();
    //     //     log_message('info', 'user/login,data:'.json_encode($data));     
    //     //     if(!$data['account'] || !$data['password'] ){
    //     //         $status = 1000;
    //     //     }
    //     //     else{
    //     //         //登陆操作
    //     //         $this->load->model("userModel");
    //     //         $status = $this->userModel->userLoginByAccount($data['account'],$data['password'],'');
    //     //     }
    //     // }
    //     // else{
    //     //     $status = 1001;
    //     // }
    //     // $this->response->sendData($status);

    // }

    /**
     * [login description
     * 手机号，短信验证码登陆（其实是绑定手机号到一个openid）
     * 从小程序进来，说明已经授权了，然后openid已经存放好，session里面已经有唯一标识了
     * 多一个参数：邀请者手机号，可空]
     * @return [type] [description]
     */
    public function loginMsg(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/loginMsg,data:'.json_encode($reqData));     
            if(!$reqData['account'] || !$reqData['code']){
                $this->response->sendData(1000);return;
            }
            
            //1验证登录状态(小程序已经登录了)       
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;
            }
            $userId = $retStatus['userId'];

            //2手机号格式
            if(strlen($reqData['account'])!=11 || !preg_match("/^1\d{10}$/", $reqData['account'])){
                $this->response->sendData(1000);return;
            }   
            //3关联账号
            $status = $this->userModel->userLoginByAccount($reqData['account'],'',$reqData['code'],$userId ,$reqData);
        }
        else{
            $status = 1001;
        }
        log_message('info', 'user/loginMsg,status:'.$status);    
        $this->response->sendData($status);

    }

    /**
     * [sendMsg description]
     * @return [type] [description]
     */
    public function sendMsg(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/sendMsg,data:'.json_encode($reqData));     
            if(!$reqData['account']){
                $this->response->sendData(1000);return;
            }

            //1验证登录状态(小程序已经登录了)       
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;
            }
            $userId = $retStatus['userId'];

            //2是否在当天超过了指定条数
            $this->load->model("msgVerifyModel");
            $total = $this->msgVerifyModel->countByAccount($reqData['account'],date("Y-m-d"));
            if($total>5){
                $this->response->sendData(2003);return;
            }
            //3是否超过了重发时限
            $repeatMsg = $this->msgVerifyModel->repeatMsg($reqData['account'],date("Y-m-d"));
            log_message('info', 'user/sendMsg,repeatMsg:'.json_encode($repeatMsg));     
            if($repeatMsg['status']==0){
                $this->response->sendData(2004);return;
            }
            //4可以发送、调用短信网关
            $code = rand(1000,9999);
            $this->load->library('shortMessage');
            $testMsg = "您的验证码为：$code 【时坊】";
            $sendStatus = $this->shortmessage->send($reqData['account'],$testMsg);
            log_message('info', 'user/sendMsg,sendStatus:'.json_encode($sendStatus));  
            if(!$sendStatus){
                //5入库
                $insert = $this->msgVerifyModel->insertOneMsg($reqData['account'],$code,10,1,0);
                if($insert>0){
                    //入库成功
                    $status = 0;
                }             
                else{
                    //入库失败
                    $status = 1002;
                }
                   
            }
            else{
                $status = 2017;
            }
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);


    }

    /**
     * [sendEmail description]
     * @return [type] [description]
     */
    public function sendEmail(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/sendEmail,data:'.json_encode($reqData)); 
            if(!$reqData['account']){
                $this->response->sendData(1000);return;
            }
            //1验证登录状态            
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;
            }
            $userId = $retStatus['userId'];

            //2校验邮箱格式
            $this->load->helper('email');
            if (!valid_email($reqData['account'])){
                $this->response->sendData(2012);return;               
            }
            
            //3发送邮件，是否在当天超过了指定条数
            $this->load->model("msgVerifyModel");
            $total = $this->msgVerifyModel->countByAccount($reqData['account'],date("Y-m-d"));
            if($total>10){
                $this->response->sendData(2003);return;
            }
            //4是否超过了重发时限
            $repeatMsg = $this->msgVerifyModel->repeatMsg($reqData['account'],date("Y-m-d"));
            log_message('info', 'user/sendEmail,repeatMsg:'.json_encode($repeatMsg));     
            if($repeatMsg['status']==0){
                $this->response->sendData(2004);return;
            }

            //5可以发送
            $emailInfo = $this->config->item('emailInfo');
            $code = rand(1000,9999);
            $from = $emailInfo['account'];
            $this->load->library('email');
            //基础配置
            $config['protocol'] = 'smtp'; 
            $config['smtp_host'] = 'smtp.126.com'; 
            $config['smtp_user'] = $from; 
            $config['smtp_pass'] = $emailInfo['password']; 
            $config['smtp_port'] = 465; 
            $config['smtp_crypto'] = 'ssl';//465端口使用ssl
            $config['smtp_timeout'] = 5; 
            $config['newline'] = "\r\n"; 
            $config['crlf'] = "\r\n"; 
            // var_dump($config);exit;
            $this->email->initialize($config);

            $this->email->from($from, '时坊');
            $this->email->to($reqData['account']);

            $this->email->subject('邮箱绑定验证码');
            $this->email->message("亲爱的:".$reqData['account'].",您好\r\n感谢您注册时坊，这是您的验证码：$code\r\n在小程序中输入验证码以绑定您的邮箱\r\n \r\n \r\n请妥善保管您的登录邮箱，我们将通过邮件发送任务文件等信息。");

            $result = $this->email->send();
            // echo $this->email->print_debugger(); exit;
            log_message('info', 'user/sendMsg,sendStatus:'.json_encode($result));  
            if($result){
                //1入库
                $insert = $this->msgVerifyModel->insertOneMsg($reqData['account'],$code,30,1,1);
                if($insert>0){
                    //入库成功
                    $status = 0;
                }             
                else{
                    //入库失败
                    $status = 1002;
                }              
            }
            else{
                $status = 2005;
            }
            
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }




    /**
     * [bindEmail description]
     * @return [type] [description]
     */
    public function bindEmail(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/bindEmail,data:'.json_encode($reqData));     
            if(!$reqData['account'] || !$reqData['code'] ){
                $this->response->sendData(1000);return;
            }

            //1验证登录状态  
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;
            }
            $userId = $retStatus['userId'];

            //2校验邮箱格式
            $this->load->helper('email');
            if (!valid_email($reqData['account'])){
                $this->response->sendData(2012);return;               
            }

            //3检查是否绑定过邮件
            $extraInfo = $this->userModel->extraInfo($userId);
            // var_dump($extraInfo);exit;
            if(isset($extraInfo->email) && $extraInfo->email){
                $this->response->sendData(2008);return;                    
            }
            //4检测此邮箱已使用，被别人
            $info = $this->userModel->extraInfoByEmail($reqData['account']);
            // var_dump($info);exit;
            if(isset($info->user_id) && $info->user_id!=$userId){
                $this->response->sendData(2013);return;                    
            }
            // var_dump($info);exit;
            //5检查code是否正确
            $this->load->model("msgVerifyModel");
            $status = $this->msgVerifyModel->checkAndUpdateCodeByAccount($reqData['account'],$reqData['code']);
            if($status){
                $this->response->sendData($status);return;                                 
            }
            //6bind即可
            $this->userModel->bindEmail($userId,$reqData['account']);
            $status = 0;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }


    /**
     * [updateExtra 更改头像(非必填)、昵称]
     * @return [type] [description]
     */
    public function updateExtra(){
        if($this->input->method()=="post"){       
            $reqData = $this->request->getPostRawData();
            log_message('info', 'user/updateExtra,data:'.json_encode($reqData));     
            if(!$reqData['nick']  ){
                //可以不传，都不传，则直接返回
                $this->response->sendData(0);return;
            }

            //1验证登录状态  
            $this->load->model("userModel");
            $retStatus =  $this->userModel->loginStatus($reqData);
            // var_dump($retStatus);exit; 
            if($retStatus['status']){
                $this->response->sendData($retStatus['status']);return;
            }
            $userId = $retStatus['userId'];

            //2修改
            $this->userModel->updateUserExtra($userId,$reqData);
            $status = 0;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }
}